<template>
<view class="container">
  <view class="my_cardVoucher_info">
    <view class="my_cardVoucher_item"><text class="my_cardVoucher_name">名称：</text><text class="text">{{verificationCodeData.title}}</text></view>
    <view class="my_cardVoucher_item"><text class="my_cardVoucher_name">兑换码：</text><text class="text">{{verificationCodeData.verifyScanCode}}</text></view>
    <view class="my_cardVoucher_item"><text class="my_cardVoucher_name">已核销：</text><text class="text">{{verificationCodeData.verifyedCount}}次</text></view>
    <view class="my_cardVoucher_item">
      <text class="my_cardVoucher_name">剩余次数：</text>
      <text class="text" v-if="verificationCodeData.availableCount>=0">{{verificationCodeData.availableCount}}次</text>
      <text class="text" v-else>无限次</text>
    </view>
    <!-- <view class='my_cardVoucher_item'><text class='my_cardVoucher_name'>详情描述：</text><text class='text'>{{verificationCodeData.description}}</text></view> -->
  </view>
  <!-- 核销列表 -->
  <view class="verification_block_title" :style="'border-left: 4rpx solid ' + platformSetting.defaultColor" v-if="verificationCodeData.unverifyRecords.length!=0">
    <text class="verification_block_title_text">选择核销类目</text>
  </view>
  <view class="verification_block" v-if="verificationCodeData.unverifyRecords.length!=0">
    <view class="verification_title">
      <checkbox-group class="verification_title_item" style="width:10%" @change="allCheckboxChange">
          <label class="checkbox">
            <checkbox value="all" v-if="allDisabledState" :checked="allSelectState"></checkbox>
            <checkbox value="all" v-else disabled :checked="allSelectState"></checkbox>
          </label>
      </checkbox-group>
      <view class="verification_title_item" style="width:20%">
        <text>套餐名称</text>
      </view>
      <view class="verification_title_item" style="width:30%">
        <text>套餐内容</text>
      </view>
      <view class="verification_title_item" style="width:20%">
        <text>总次数</text>
      </view>
      <view class="verification_title_item" style="width:20%">
        <text>已核销</text>
      </view>
    </view>
    <checkbox-group @change="checkboxChange" class="verification_list">
      <label class="checkbox verification_item" v-for="(item, index) in verificationCodeData.unverifyRecords" :key="index">
        <checkbox v-if="item.disabled" class="verification_item_data" :value="index" :checked="item.state" style="width:10%"></checkbox>
        <checkbox v-else class="verification_item_data" disabled :value="index" :checked="item.state" style="width:10%"></checkbox>
        <text class="verification_item_data" style="width:20%">{{item.name}}</text>
        <text class="verification_item_data" style="width:30%">{{item.remark}}</text>
        <text class="verification_item_data" style="width:20%">{{item.count==-1?'无限次':item.count}}次</text>
        <text class="verification_item_data" style="width:20%">{{item.exhauseCount}}次</text>
      </label>
    </checkbox-group>
  </view>
  <!-- 已核销列表 -->
  <view class="verification_block_title" :style="'border-left: 4rpx solid ' + platformSetting.defaultColor" v-if="verificationCodeData.verifyRecords.length!=0">
    <text class="verification_block_title_text">已核销列表</text>
  </view>
  <view class="verification_block" v-if="verificationCodeData.verifyRecords.length!=0">
    <view class="verification_title">
      <view class="verification_title_item" style="width:20%">
        <text>操作人</text>
      </view>
      <view class="verification_title_item" style="width:40%">
        <text>核销内容</text>
      </view>
      <view class="verification_title_item" style="width:40%">
        <text>核销时间</text>
      </view>
    </view>
    <view @change="checkboxChange" class="verification_list">
      <view class="checkbox verification_item" v-for="(item, index) in verificationCodeData.verifyRecords" :key="index">
        <text class="verification_item_data" style="width:20%">{{item.operatorPlatformUserName}}</text>
        <text class="verification_item_data" style="width:40%">{{item.orderProcess}}</text>
        <text class="verification_item_data" style="width:40%">{{item.processTime}}</text>
      </view>
    </view>
  </view>
  <view class="verification_btn_block" v-if="verificationCodeData.availableCount">
    <view class="verification_btn" :style="'background:' + (verificationCodeData.availableCount<=0?'#ccc':platformSetting.defaultColor)" @tap="repVerificationResults">
      <text>确认核销</text>
    </view>
    <view class="verification_btn1" :style="'background:' + platformSetting.defaultColor" @tap="continueVerificationResults">
      <text>继续核销</text>
    </view>
  </view>
</view>
</template>

<script>


export default {
  data() {
    return {
      verificationCodeData: {},
      allSelectState: false,
      allDisabledState: true,
      onloadOpt: {},
      platformSetting: "",
      loginUser: ""
    };
  },

  props: {},
  onLoad: function (options) {
    let that = this;
    that.onloadOpt = options;
    console.log("==options===", options);

    if (getApp().globalData.loginUser) {
      this.checkState();
    } else {
      getApp().globalData.addLoginListener(this);
      getApp().globalData.showToastLoading('loading', true);
      console.log("====setTimeout1=====");
      that.setTimeoutLogin(that.conut);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setData({});
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
      let that = this;
      if (getApp().globalData.loginUser) {
        that.checkState();
      } else {
        getApp().globalData.addLoginListener(that); 
        getApp().globalData.showToastLoading('loading', true);
        console.log("====setTimeout1=====");
        that.setTimeoutLogin(that.conut);
      }
      wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  methods: {
    allCheckboxChange: function (e) {
      let that = this;
      console.log('allCheckboxChange-checkbox发生change事件，携带value值为：', e.detail.value[0]);
      let allSelectState = false;

      if (e.detail.value[0]) {
        allSelectState = true;
      }

      let count = 0;
      let verificationCodeData = that.verificationCodeData;

      if (verificationCodeData.unverifyRecords.length != 0) {
        for (let i = 0; i < verificationCodeData.unverifyRecords.length; i++) {
          if (verificationCodeData.unverifyRecords[i].disabled) {
            verificationCodeData.unverifyRecords[i].state = allSelectState ? true : false;
          }
        }
      }

      that.setData({
        allSelectState: allSelectState,
        verificationCodeData: verificationCodeData
      });
    },
    checkboxChange: function (e) {
      let that = this;
      console.log('checkboxChange-checkbox发生change事件，携带value值为：', e.detail.value);
      let selectData = e.detail.value;
      let verificationCodeData = that.verificationCodeData;
      let allSelectState = false;
      let count = 0;

      if (selectData.length != 0) {
        for (let i = 0; i < verificationCodeData.unverifyRecords.length; i++) {
          verificationCodeData.unverifyRecords[i].state = false;

          if (verificationCodeData.unverifyRecords[i].disabled) {
            count++;
          }
        }

        for (let i = 0; i < selectData.length; i++) {
          verificationCodeData.unverifyRecords[selectData[i]].state = true;
        }
      } else {
        allSelectState = false;

        for (let i = 0; i < verificationCodeData.unverifyRecords.length; i++) {
          verificationCodeData.unverifyRecords[i].state = false;
        }
      }

      console.log("===count===", count);

      if (selectData.length == count) {
        allSelectState = true;
      }

      that.setData({
        allSelectState: allSelectState,
        verificationCodeData: verificationCodeData
      });
    },
    getVerificationCode: function () {
      var that = this;
      var customIndex = getApp().globalData.AddClientUrl("/wx_get_scan_verify_parameter.html", that.onloadOpt);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log("getVerificationCode", res.data);
          let verificationCodeData = res.data.relateObj;
          let count = 0;
          let allDisabledState = true;
          that.onloadOpt = Object.assign({}, that.onloadOpt, {
            verifySign: verificationCodeData.sign,
            verifySeq: verificationCodeData.seq
          });

          if (verificationCodeData.unverifyRecords.length != 0) {
            for (let i = 0; i < verificationCodeData.unverifyRecords.length; i++) {
              verificationCodeData.unverifyRecords[i].state = false;

              if (verificationCodeData.unverifyRecords[i].count!=-1&&verificationCodeData.unverifyRecords[i].count <= verificationCodeData.unverifyRecords[i].exhauseCount) {
                verificationCodeData.unverifyRecords[i].disabled = false;
                count++;
              } else {
                verificationCodeData.unverifyRecords[i].disabled = true;
              }
            }
          }

          if (count == verificationCodeData.unverifyRecords.length) {
            allDisabledState = false;
          }

          console.log("====verificationCodeData===", verificationCodeData);
          that.setData({
            allSelectState: false,
            allDisabledState: allDisabledState,
            verificationCodeData: verificationCodeData
          });
        },
        complete: function (res) {}
      });
    },
    getVerificationResults: function () {
      var that = this;
      let exhauseItems = [];
      let verificationCodeData = that.verificationCodeData;

      if (verificationCodeData.unverifyRecords.length != 0) {
        for (let i = 0; i < verificationCodeData.unverifyRecords.length; i++) {
          if (verificationCodeData.unverifyRecords[i].state) {
            let itemData = {
              name: verificationCodeData.unverifyRecords[i].name,
              count: 1
            };
            exhauseItems.push(itemData);
          }
        }

        that.onloadOpt = Object.assign({}, that.onloadOpt, {
          exhauseItems: encodeURIComponent(JSON.stringify(exhauseItems))
        });
      }
      if (exhauseItems.length == 0) {
        wx.showModal({
          title: '警告',
          content: '请您选择一项核销！！'
        });
        return;
      }

      console.log("that.onloadOpt", that.onloadOpt);
      var customIndex = getApp().globalData.AddClientUrl("/wx_scan_verify.html", that.onloadOpt);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log("getVerificationResults", res.data);
          that.getVerificationCode();
          if (res.data.errcode == 0) {
            wx.showToast({
              title: res.data.relateObj,
              icon: 'success',
              duration: 2000
            });
          } else {
            wx.showModal({
              title: '错误',
              content: res.data.errMsg,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              }
            });
          }
        },
        complete: function (res) {}
      });
    },
    repVerificationResults: function () {
      this.tipFun("主人~您确认要核销吗？");
    },
    continueVerificationResults: function () {
      wx.scanCode({
        onlyFromCamera: true,
        success: scanRes => {
          console.log("getVerificationCode", scanRes);
          wx.navigateTo({
            url: "/" + scanRes.path
          });
        }
      });
    },
    tipFun: function (data) {
      let that = this;
      wx.showModal({
        title: '提示',
        content: data.relateObj || data,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            that.getVerificationResults();
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    setNavColor: function () {
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: getApp().globalData.setting.platformSetting.defaultColor
      });
    },
    loginSuccess: function (user) {
      console.log("pre apply mendian login success call back!", user);
      this.checkState();
    },
    loginFailed: function (err) {
      console.log("login failed!!");
    },
    checkState: function () {
      console.log('======checkState.loginUser======', getApp().globalData.loginUser);
      this.setData({
        platformSetting: getApp().globalData.setting.platformSetting,
        loginUser: getApp().globalData.loginUser
      });
      this.setNavColor();
      this.getVerificationCode();
    },
    setTimeoutLogin: function (conuData) {
      let that = this;
      console.log("====setTimeout-init=====", conuData);
      that.conut = conuData;
      that.conut += 2;

      if (that.conut <= 6) {
        setTimeout(function () {
          if (getApp().globalData.loginUser) {
            wx.hideLoading();
          } else {
            that.setTimeoutLogin(that.conut);
          }
        }, that.conut * 1000);
      } else {
        wx.hideLoading();
        // wx.showModal({
        //   title: '失败了',
        //   content: '请求失败了，请下拉刷新！'
        // });
        let url="verification_results.html?code="+that.onloadOpt.code+"&verifyScanType="+that.onloadOpt.verifyScanType
        let backUrl=encodeURIComponent(url)
        getApp().globalData.checkIfLogin(backUrl)
      }
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>